package com.mynews.activities.tipoff;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.mynews.activities.App;
import com.mynews.activities.detail.DetailActivity;
import com.mynews.adapter.TipOffAdp;
import com.mynews.bean.NewsBean;
import com.mynews.bean.TipOffBean;
import com.mynews.bean.User;
import com.mynews.databinding.ActivityTipoffBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class TipOffVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")
    private ActivityTipoffBinding binding;
    @SuppressLint("StaticFieldLeak")
    private TipOffActivity tipOffActivity;
    private final List<TipOffBean> data=new ArrayList<>();
    public TipOffVM(@NonNull Application application) {
        super(application);
    }
    public void setBinding(ActivityTipoffBinding binding, TipOffActivity tipOffActivity) {
        this.binding=binding;
        this.tipOffActivity=tipOffActivity;
        binding.setAdp(new TipOffAdp(tipOffActivity,data));
        binding.tipoffList.setOnItemClickListener((parent, view, position, id) -> {
            TipOffBean bean = data.get(position);
            if (bean.newsId.equals("")){
                Toast.makeText(tipOffActivity, "该新闻已被删除", Toast.LENGTH_SHORT).show();
                BmobApi.delete("https://api2.bmob.cn/1/classes/tipoff/"+data.get(position).id, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        tipOffActivity.runOnUiThread(() -> {
                            Toast.makeText(tipOffActivity, "该举报信息已经自动删除", Toast.LENGTH_SHORT).show();
                            refresh();
                        });
                    }
                });
            }else {
                App.newsBean=bean.newsBean;
                tipOffActivity.startActivity(new Intent(tipOffActivity, DetailActivity.class));
            }
        });
        binding.tipoffList.setOnItemLongClickListener((parent, view, position, id) -> {
            TipOffBean bean = data.get(position);
            if (bean.newsId.equals("")){
                Toast.makeText(tipOffActivity, "该新闻已被删除", Toast.LENGTH_SHORT).show();
                BmobApi.delete("https://api2.bmob.cn/1/classes/tipoff/"+data.get(position).id, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        tipOffActivity.runOnUiThread(() -> {
                            Toast.makeText(tipOffActivity, "该举报信息已经自动删除", Toast.LENGTH_SHORT).show();
                            refresh();
                        });
                    }
                });
            }else {
                AlertDialog.Builder dialog=new AlertDialog.Builder(tipOffActivity);
                dialog.setTitle("提示").setMessage("是否撤销此举报？").setPositiveButton("撤销", (dialog1, which) -> BmobApi.delete("https://api2.bmob.cn/1/classes/tipoff/"+data.get(position).id,new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e){}
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        refresh();
                    }
                })).setNeutralButton("不撤销",null).show();
            }
            return true;
        });
        refresh();
    }
    private void refresh() {
        data.clear();
        BmobApi.get("https://api2.bmob.cn/1/classes/tipoff?include=news,user,newsOwner&where={\"userId\":\""+ App.user.objectId+"\"}", new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = ja.getJSONObject(i);
                        JSONObject jo_news = jo.getJSONObject("news");
                        JSONObject jo_user = jo.getJSONObject("user");
                        JSONObject newsOwner = jo.getJSONObject("newsOwner");
                        User news_user= new User(newsOwner.getString("email"), "", newsOwner.getString("objectId"), newsOwner.getString("username"), newsOwner.getString("nickname"), newsOwner.getBoolean("isAdmin"));
                        if (jo_news.isNull("objectId")){
                            data.add(new TipOffBean(jo.getString("objectId"),jo_user.getString("objectId"),"",jo.getString("content"),jo.getString("createdAt"),jo_user.getString("nickname"),new NewsBean("","该新闻已被删除","无内容：该新闻已被删除","","已删除",null,news_user),jo.getString("process")));
                        }else{
                            data.add(new TipOffBean(jo.getString("objectId"),jo_user.getString("objectId"),jo_news.getString("objectId"),jo.getString("content"),jo.getString("createdAt"),jo_user.getString("nickname"),new NewsBean(jo_news.getString("objectId"),jo_news.getString("title"),jo_news.getString("content"),jo_news.getString("ownerId"),jo_news.getString("createdAt"),null,news_user),jo.getString("process")));
                        }
                    }
                    tipOffActivity.runOnUiThread(() -> binding.getAdp().notifyDataSetChanged());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
